package com.axend.sofa.ui.activity

import android.content.Intent
import android.os.Bundle
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.axend.lib_base.bean.SofaModelEntity
import com.axend.lib_base.engine.toast.toast
import com.axend.lib_base.ext.click
import com.axend.lib_base.ext.dp2px
import com.axend.lib_base.help.ble.BleMsgProcessor
import com.axend.lib_base.help.ble.enums.BleCommandTag
import com.axend.lib_base.livedatabus.LiveDatabus
import com.axend.lib_base.utils.ActivityManage
import com.axend.lib_base.view.dialog.CustomCalibrationDialog
import com.axend.sofa.base.BaseBleVVDActivity
import com.axend.lib_service.ARouterPath
import com.axend.lib_service.Constant
import com.axend.sofa.BR
import com.axend.sofa.R
import com.axend.sofa.adapter.BleModelAdapter
import com.axend.sofa.databinding.ActivitySelectModelBinding
import com.axend.sofa.viewmodel.SelectModelViewModel
import com.hjq.permissions.OnPermissionCallback
import com.hjq.permissions.Permission
import com.hjq.permissions.XXPermissions
import com.yxing.ScanCodeConfig
import com.yxing.def.ScanMode
import com.yxing.def.ScanStyle
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.launch
import javax.annotation.Nullable
import javax.inject.Inject

/**
 * @description 选择设备型号
 * @author admins
 * @time 2025/3/5 9:21
 */
@AndroidEntryPoint
@Route(path = ARouterPath.ACTIVITY_SELECT_MODEL)
class SelectModelActivity : BaseBleVVDActivity<SelectModelViewModel, ActivitySelectModelBinding>() {

    @Autowired(name = Constant.ROUTER_KEY_MODEL_SELECT)
    @JvmField
    var model: Int = 0

    @Inject
    lateinit var bleModelAdapter: BleModelAdapter

    /*校准弹窗*/
    private val dialog: CustomCalibrationDialog by lazy {
        CustomCalibrationDialog(
            this,
            {ActivityManage.finishActivity(this@SelectModelActivity)}
        ) {
            /*停止学习*/
            mViewModel.writeBleMsg(
                BleMsgProcessor.encodeMsg(
                    BleCommandTag.SET_STUDY_END.getMarkFixCommand(),
                    BleCommandTag.SET_STUDY_END
                )
            )
        }
    }

    override fun init(savedInstanceState: Bundle?) {
        super.init(savedInstanceState)
        ARouter.getInstance().inject(this)
        // set viewModel
        mBinding.setVariable(BR.viewmodel, mViewModel)
        mBinding.executePendingBindings()
        // set adapter
        mBinding.rvList.apply {
            layoutManager = LinearLayoutManager(this@SelectModelActivity)
            adapter = bleModelAdapter
            setHasFixedSize(true)
        }

        mViewModel.modelData.observe(this) {
            bleModelAdapter.setList(it)
        }

        mViewModel.dialogModel.observe(this) {
            dialog.setModel(it)
        }
        mViewModel.setCalibrationEnable(model!=0)
        /*初始化数据*/
        mViewModel.addModelData(
            listOf(
                SofaModelEntity(model = 0, modelName = "0(Not set)", isSelect = model == 0),
                SofaModelEntity(
                    model = 1,
                    modelName = "7710196(double recliner)",
                    isSelect = model == 1
                ),
                SofaModelEntity(
                    model = 2,
                    modelName = "6930582(big range recliner)",
                    isSelect = model == 2
                ),
                SofaModelEntity(
                    model = 3,
                    modelName = "7650498(rocker recliner)",
                    isSelect = model == 3
                ),
                SofaModelEntity(
                    model = 4,
                    modelName = "8530512(lift recliner front)",
                    isSelect = model == 4
                ),
                SofaModelEntity(
                    model = 5,
                    modelName = "8530512(lift recliner back)",
                    isSelect = model == 5
                ),
            )
        )

        bleModelAdapter.setOnItemChildClickListener { adapter, view, position ->
            for (i in 0 until bleModelAdapter.data.size) {
                bleModelAdapter.data[i]?.let {
                    it.isSelect = false
                }
            }
            adapter.notifyDataSetChanged()
            val item = bleModelAdapter.getItem(position)
            item?.let {
                it.isSelect = !it.isSelect
            }
//            LiveDatabus.getInstance().withSticky(Constant.EVENT_BUS_KEY_MODEL, Int::class.java)
//                .postValue(item.model)
            mViewModel.writeBleMsg(
                BleMsgProcessor.encodeMsg(item.model, BleCommandTag.SET_SOFA_MODEL),
                item.model
            )
            adapter.setData(position, item)
        }

        mBinding.titleBar.rightLayout.click {
            XXPermissions.with(this@SelectModelActivity).permission(Permission.CAMERA)
                .permission(Permission.ACCESS_COARSE_LOCATION)
                .request(object : OnPermissionCallback {
                    override fun onGranted(permissions: MutableList<String>, allGranted: Boolean) {
                        LiveDatabus.getInstance()
                            .withSticky(Constant.EVENT_BUS_KEY_SCAN_TITLE, String::class.java)
                            .postValue(getString(R.string.app_bar_title_scan_qr_code_model))
                        ScanCodeConfig.create(this@SelectModelActivity)
                            //设置扫码页样式 ScanStyle.NONE：无  ScanStyle.QQ ：仿QQ样式   ScanStyle.WECHAT ：仿微信样式  ScanStyle.CUSTOMIZE ： 自定义样式
                            .setStyle(ScanStyle.CUSTOMIZE)
                            //扫码成功是否播放音效  true ： 播放   false ： 不播放
                            .setPlayAudio(true)
                            //设置音效音频
//                .setAudioId(com.axend.sofa.R.raw.beep) ////////////////////////////////////////////
                            //以下配置 在style为 ScanStyle.CUSTOMIZE 时生效
                            //设置扫码框位置  left ： 边框左边位置   top ： 边框上边位置   right ： 边框右边位置   bottom ： 边框下边位置   单位/dp
                            //                                    .setScanRect(new ScanRect(50, 200, 300, 450), false)
                            //是否限制识别区域为设定扫码框大小  true:限制  false：不限制   默认false：识别区域为整个屏幕
                            .setLimitRect(true)
                            //设置扫码框位置 scanSize : 扫码框大小   offsetX ： x轴偏移量    offsetY ：y轴偏移量   单位 /px
                            .setScanSize(dp2px(300f), 0, 0)
                            //是否显示边框上四个角标 true ： 显示  false ： 不显示
                            .setShowFrame(true)
                            //设置边框上四个角标颜色
                            .setFrameColor(com.axend.lib_base.R.color.green_level_3)
                            //设置边框上四个角标圆角  单位 /dp
                            .setFrameRadius(2)
                            //设置边框上四个角宽度 单位 /dp
                            .setFrameWith(1)
                            //设置边框上四个角长度 单位 /dp
                            .setFrameLength(200)
                            //设置是否显示边框外部阴影 true ： 显示  false ： 不显示
                            .setShowShadow(true)
                            //设置边框外部阴影颜色
                            .setShadeColor(com.axend.lib_base.R.color.black_tran_level_1)
                            //设置扫码条运动方式   ScanMode.REVERSE : 往复运动   ScanMode.RESTART ：重复运动    默认ScanMode.RESTART
                            .setScanMode(ScanMode.REVERSE)
                            //设置扫码条扫一次时间  单位/ms  默认3000
                            .setScanDuration(3000) //设置扫码条图片
//                .setScanBitmapId(R.mipmap.scan_wechatline) //////////////////////////////////////////////
                            //以下配置在 setIdentifyMultiple 为 true 时生效
                            //设置是否开启识别多个二维码 true：开启 false：关闭   开启后识别到多个二维码会停留在扫码页 手动选择需要解析的二维码后返回结果
                            .setIdentifyMultiple(false)
                            //设置 二维码提示按钮的宽度 单位：px
                            .setQrCodeHintDrawableWidth(120)
                            //设置 二维码提示按钮的高度 单位：px
                            .setQrCodeHintDrawableHeight(120)
                            //设置 二维码提示按钮的Drawable资源
                            //.setQrCodeHintDrawableResource(R.mipmap.in)
                            //设置 二维码提示Drawable 是否开启缩放动画效果
                            .setStartCodeHintAnimation(true)
                            //设置 二维码选择页 背景透明度
                            .setQrCodeHintAlpha(0.5f)
                            .buidler()
                            //跳转扫码页   扫码页可自定义样式
                            .start(ScanQRCodeActivity::class.java)

                    }


                    override fun onDenied(
                        permissions: MutableList<String>,
                        doNotAskAgain: Boolean
                    ) {
                        if (doNotAskAgain) {
                            toast(getString(com.axend.lib_base.R.string.app_tips_permission_grant))
                            XXPermissions.startPermissionActivity(
                                this@SelectModelActivity,
                                permissions
                            )
                        } else {
                            toast(getString(com.axend.lib_base.R.string.app_tips_permission_fail))
                        }
                    }

                })

        }

        mBinding.btNext.click {
            /*开始学习*/
            mViewModel.writeBleMsg(
                BleMsgProcessor.encodeMsg(
                    BleCommandTag.GET_VERSION.getMarkFixCommand(),
                    BleCommandTag.SET_STUDY_START
                )
            )
        }

    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, @Nullable data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == RESULT_OK && data != null) {
            when (requestCode) {
                ScanCodeConfig.QUESTCODE -> {
                    //接收扫码结果
                    val extras = data.extras
                    if (extras != null) {
                        val codeType = extras.getInt(ScanCodeConfig.CODE_TYPE)
                        val code = extras.getString(ScanCodeConfig.CODE_KEY)
                        if (code.isNullOrEmpty()) {
                            toast(getString(com.axend.lib_base.R.string.app_no_record))
                            return
                        }
                        for (i in 0 until bleModelAdapter.data.size) {
                            bleModelAdapter.data[i]?.let {
                                it.isSelect = it.model==code.toInt()
                            }

                        }
                        bleModelAdapter.notifyDataSetChanged()

                        mViewModel.writeBleMsg(
                            BleMsgProcessor.encodeMsg(code, BleCommandTag.SET_SOFA_MODEL),
                            code
                        )

                    }
                }

//                ALBUM_QUEST_CODE -> {
//                    //接收图片识别结果
//                    val code = ScanCodeConfig.scanningImage(this, data.data)
//                    tvCode.setText(String.format("识别结果： %s", code))
//                }

                else -> {}
            }
        }
    }
}